import hashlib
import json
import random

import requests

from xuanba_setting import app

ALL_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'


def random_captcha_text(length=4):
    """随机生成验证码字符串"""
    return ''.join(random.choices(ALL_CHARS, k=length))


def gen_mobile_code(length=6):
    """生成指定长度的手机验证码"""
    return ''.join(random.choices('0123456789', k=length))


@app.task
def send_sms_by_luosimao(tel, message):
    """发送短信（调用螺丝帽短信网关）"""
    resp = requests.post(
        url='http://sms-api.luosimao.com/v1/send.json',
        auth=('api', 'key-9553a312962e997c4c71dfb9115a1c45'),
        data={
            'mobile': tel,
            'message': message
        },
        timeout=10,
        verify=False)
    return json.loads(resp.content)


def to_md5_hex(content):
    """生成字符串的MD5摘要"""
    return hashlib.md5(content.encode()).hexdigest()